package fm.dongman.animefm.view.listener

import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView


/**
 * 滑动加载更多，滑动抽象类
 * Created by shize on 2017/11/4.
 */
abstract class LoadMoreRecyclerOnScrollListener constructor(private val mLayoutManager: RecyclerView.LayoutManager)
    : RecyclerView.OnScrollListener() {

    private var previousTotal = 0
    private var loading = true
    private var firstVisibleItem: Int = 0
    private var visibleItemCount: Int = 0
    var totalItemCount: Int = 0

    private var currentPage = 1

    override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
        super.onScrolled(recyclerView, dx, dy)

        visibleItemCount = recyclerView!!.childCount
        totalItemCount = mLayoutManager.itemCount
        firstVisibleItem = (mLayoutManager as? LinearLayoutManager)?.findFirstVisibleItemPosition() ?:
                if (mLayoutManager is GridLayoutManager) {
                    mLayoutManager.findFirstVisibleItemPosition()
                } else {
                    throw TypeCastException("加载更多功能不支持当前布局！！！")
                }

        if (loading) {
            if (totalItemCount > previousTotal) {
                loading = false
                previousTotal = totalItemCount
            }
        }
        if (!loading && totalItemCount - visibleItemCount <= firstVisibleItem) {
            currentPage++
            onLoadMore(currentPage)
            loading = true
        }
    }

    /**
     * 清除页
     */
    fun clearPage(){
        previousTotal = 0
        loading = true
        firstVisibleItem = 0
        visibleItemCount = 0
        totalItemCount = 0
        currentPage = 1
    }

    /**
     * 加载更多
     * @param currentPage 当前页数，初始为 1 页，每次加载更多则增加一页
     */
    abstract fun onLoadMore(currentPage: Int)
}